package cn.wolfcode.luowowo.website.controller;


import cn.wolfcode.luowowo.article.domain.Destination;
import cn.wolfcode.luowowo.article.domain.StrategyDetail;
import cn.wolfcode.luowowo.article.domain.Travel;
import cn.wolfcode.luowowo.article.service.IDestinationService;
import cn.wolfcode.luowowo.article.service.IStrategyDetailService;
import cn.wolfcode.luowowo.article.service.ITravelService;
import cn.wolfcode.luowowo.cache.key.RedisKey;
import cn.wolfcode.luowowo.cache.service.IStrategyStatsCacheService;
import cn.wolfcode.luowowo.cache.service.ITravelStatsCacheService;
import cn.wolfcode.luowowo.cache.service.IUserInfoCacheService;
import cn.wolfcode.luowowo.comment.domain.TravelComment;
import cn.wolfcode.luowowo.comment.service.ITravelCommentService;
import cn.wolfcode.luowowo.common.query.TravelQueryObject;
import cn.wolfcode.luowowo.common.util.AjaxResult;
import cn.wolfcode.luowowo.member.domain.UserInfo;
import cn.wolfcode.luowowo.website.annotation.LoginUser;
import cn.wolfcode.luowowo.website.annotation.RequireLogin;
import cn.wolfcode.luowowo.website.util.UMEditorUploader;
import cn.wolfcode.luowowo.website.util.UploadUtil;
import com.github.pagehelper.PageInfo;
import org.apache.dubbo.config.annotation.Reference;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Controller
@RequestMapping("/travel")
public class TravelController {
    @Reference
    private ITravelService travelService;
    @Reference
    private ITravelStatsCacheService travelStatsCacheService;
    @Reference
    private IUserInfoCacheService userInfoCacheService;

    @RequestMapping("")
    public String list(@ModelAttribute("qo")TravelQueryObject qo, Model model){
        PageInfo pageInfo = travelService.query(qo);
        model.addAttribute("pageInfo",pageInfo);
        return "travel/list";
    }

    @Reference
    private IDestinationService destinationService;
    @Reference
    private IStrategyDetailService strategyDetailService;
    /**
     * 根据id查询文章信息
     * @param id
     * @param model
     * @return
     */
    @RequestMapping("/detail")
    public String detail(Long id,Model model ,@LoginUser UserInfo user) throws Exception {
        //通过游记的id查询出来游记的作者
        Long authorId = travelService.selectByTravel(id);
        if (user != null){
            //设置文章作者访客量
            userInfoCacheService.setVisitors(authorId,user.getId());
        }
        //获取用户的id和游记的id,作为key存入redis中
        String cacheKey =null;
        if(user!=null){
            String key = id.toString()+":" + user.getId().toString();
            cacheKey = RedisKey.TRAVEL_STATS.getCacheKey(key);

        //获取当前时间作为访问时间value存入
        Date date = new Date();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        String createdate = sdf.format(date);
        //把数据存入到redis中id
        travelStatsCacheService.setVisitTime(cacheKey,createdate);
        //表示该游记被访问,访问量+1
         travelStatsCacheService.incrNum(id, 1, ITravelStatsCacheService.Travel_STATS_VIEWNUM);
        //把登录的用户访问的用户存入list集合中
        List<String> UserList = new ArrayList<>();
        UserList.add(cacheKey);
        }



        //游记文章内容detail
        Travel travel = travelService.get(id);
        //目的地id
        Long destId = travel.getDest().getId();
        model.addAttribute("detail",travel);
        //toasts
        List<Destination> toasts = destinationService.listToasts(destId);
        model.addAttribute("toasts",toasts);
        //sds 点击量前三的相关攻略,根据当前游记的目的地id查询
        List<StrategyDetail> sds = strategyDetailService.listVeiwnumTop3(destId);
        model.addAttribute("sds",sds);
        //ts 查询当前目的地下阅读量前三的游记
        List<Travel> ts = travelService.listVeiwnumTop3(destId);
        model.addAttribute("ts",ts);
        //list
        model.addAttribute("list",travelCommentService.listCommentByDetailId(id));
        //vo
        model.addAttribute("vo",travelStatsCacheService.getTravelStats(id));
        return "travel/detail";
    }


    @RequireLogin
    @RequestMapping("/input")
    public String input(Long id,Model model){
        //dests
        List<Destination> dests = destinationService.listAll();
        model.addAttribute("dests",dests);
        //tv
        if (id != null){
            Travel tv = travelService.get(id);
            model.addAttribute("tv",tv);
        }
        return "travel/input";
    }
    @Value("${file.dir}")
    private String filePath;

    //上传图片
    @RequestMapping("/coverImageUpload")
    @ResponseBody
    public Object coverImageUpload(MultipartFile pic){
        String upload = UploadUtil.upload(pic, filePath);
        return upload;
    }

    //上传图片
    @RequestMapping("/contentImage")
    @ResponseBody
    public String uploadUEImage(MultipartFile upfile,HttpServletRequest request) throws Exception{
        UMEditorUploader up = new UMEditorUploader(request);
        String[] fileType = {".gif" , ".png" , ".jpg" , ".jpeg" , ".bmp"};
        up.setAllowFiles(fileType);
        up.setMaxSize(10000); //单位KB
        up.upload(upfile, filePath);

        String callback = request.getParameter("callback");
        String result = "{\"name\":\""+ up.getFileName() +"\", \"originalName\": \""+ up.getOriginalName() +"\", \"size\": "+ up.getSize()
                +", \"state\": \""+ up.getState() +"\", \"type\": \""+ up.getType() +"\", \"url\": \""+ up.getUrl() +"\"}";
        result = result.replaceAll( "\\\\", "\\\\" );
        if(callback == null ){
            return result ;
        }else{
            return "<script>"+ callback +"(" + result + ")</script>";
        }
    }


    @RequestMapping("/getContent")
    @ResponseBody
    public Object getContent(Long id){
        return travelService.getContent(id);
    }

    @RequireLogin
    @RequestMapping("/saveOrUpdate")
    @ResponseBody
    public Object saveOrUpdate(Travel travel, @LoginUser UserInfo user){
        //如果是更新,登陆者只能改自己的文章
        if(travel.getId() != null){
            //查询文章的作者
            Travel tv = travelService.get(travel.getId());
            //如果id不一致,不能更改
            if (!tv.getAuthor().getId().equals(user.getId())){
                AjaxResult result = new AjaxResult();
                result.mark("操作失败");
                return result;
            }
        }
        //设置当前登录的游记作者
        travel.setAuthor(user);
        return travelService.saveOrUpdate(travel);
    }

    @Reference
    private ITravelCommentService travelCommentService;

    @RequireLogin
    @RequestMapping("commentAdd")
    public String commentAdd(TravelComment comment,Integer floor,
                             @LoginUser UserInfo user,Model model){
        //填充用户信息
        comment.setUserId(user.getId());
        comment.setHeadUrl(user.getHeadImgUrl());
        comment.setUsername(user.getNickname());
        comment.setLevel(user.getLevel());

        //保存评论,并返回评论对象
        TravelComment c = travelCommentService.commentAdd(comment);

        //共享保存的评论对象
        model.addAttribute("c",c);
        //floor
        model.addAttribute("floor",floor + 1 );
        return "travel/commentTpl";
    }

    @RequestMapping("share")
    @ResponseBody
    public Object share(Long strategyId){
        AjaxResult result = new AjaxResult();
        travelStatsCacheService.incrNum(strategyId,1,ITravelStatsCacheService.TRAVEL_STATS_SHARENUM);
        return result;

    }

    //收藏游记
    @RequestMapping("favors")
    @ResponseBody
    @RequireLogin
    public Object share(@LoginUser UserInfo user, Long travelId) {
        AjaxResult result = new AjaxResult();
        boolean isFavor = true;
        if (user == null) {
            result.mark("请先登录");
            result.setCode(102);
            return result;
        }
        boolean flag = travelStatsCacheService.favor(travelId, user.getId());
        result.setSuccess(flag);
        return result;
    }
}
